package com.utils;




import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.test.TestCinema;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBPoolUtils2 {
    public  static DataSource ds=null;

    private DBPoolUtils2(){};


    public  static DataSource getDataSource(){
        if(ds==null){
            synchronized (DBPoolUtils2.class){
                if (ds==null){
                    try {
                        ds= DruidDataSourceFactory.createDataSource(getProperties("db.properties"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return ds;
    }

    public static Connection getConnection(){
        try {
            return  ds==null?null:ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;

    }

    public  static Properties getProperties(String propertiesName)  {
        String  path= TestCinema.class.getResource("/").getPath()+propertiesName;

        try {
            path= URLDecoder.decode(path,"UTF-8");

            Properties p=new Properties();
            p.load(new FileInputStream(path));

            return p;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
     return null;

    }
}
